package com.fish.yssb.wave;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.fish.yssb.db.bean.BaseInfoTable;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;


/**
 * Used 尺寸转换工具类（全）
 */

/**
 * 读取Excel
 */
public class WaveControl {
    /**Sheet表, Excel表中的底部的表名*/
    private WritableSheet mWritableSheet;
    /**Excel工作簿*/
    private WritableWorkbook mWritableWorkbook;

    private static String cfgPath="/111/66.cfg";
    private static String datPath="/111/66.dat";;


    private static WaveInfo waveInfo;

    public static WaveInfo  getData()
    {
        try {
//            char[] str = new char[50 * 1024 * 1024];
            String strCfg = ReadTxtFile(getSDPath() + cfgPath);
//            String strdat = ReadDatFile(getSDPath() + datPath, str);
           byte[] bytes =   readLocalFile(getSDPath() + datPath);
            String strCC[] = strCfg.split("\n");
            waveInfo = new WaveInfo();
            waveInfo = WaveInfoJX.parseData(strCC);

            waveInfo = PassSubInfoJX.parseData(bytes,waveInfo);
        }catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return  waveInfo;
    }

    private static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();
        }
        String dir = sdDir.toString();
        return dir;
    }

    /**
     * 判断文件的编码格式
     * @param fileName :file
     * @return 文件编码格式
     */
    public static String codeString(String fileName) {
        String code = null;
        try {
            BufferedInputStream bin = new BufferedInputStream(
                    new FileInputStream(fileName));
            int p = (bin.read() << 8) + bin.read();


            switch (p) {
                case 0xefbb:
                    code = "UTF-8";
                    break;
                case 0xfffe:
                    code = "Unicode";
                    break;
                case 0xfeff:
                    code = "UTF-16BE";
                    break;
                default:
                    code = "GBK";
            }
        }catch (Exception ex)
        {
            ex.printStackTrace();
        }

        return code;
    }

    private static byte[] toByteArray(InputStream in)  {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            byte[] buffer = new byte[1024 * 4];
            int n = 0;
            while ((n = in.read(buffer)) != -1) {
                out.write(buffer, 0, n);
            }
        }catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return out.toByteArray();
    }

    private static byte[] readLocalFile(String strFilePath) throws IOException {


        //打开文件
        File file = new File(strFilePath);
        //如果path是传递过来的参数，可以做一个非目录的判断
        if (file.isDirectory())
        {
            Log.d("TestFile", "The File doesn't not exist.");
        }
        InputStream inputStream =  new FileInputStream(file);
        byte[] data = toByteArray(inputStream);

        String str =  bytesToHex(data);
        inputStream.close();
        return data;
    }


    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if(hex.length() < 2){
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }



    public static String ReadDatFile(String strFilePath,char[] a)
    {
        String content = ""; //文件内容字符串
        String path = strFilePath;


        //打开文件
        File file = new File(path);
        //如果path是传递过来的参数，可以做一个非目录的判断
        if (file.isDirectory())
        {
            Log.d("TestFile", "The File doesn't not exist.");
        }
        try {
            codeString(strFilePath);
                InputStream instream = new FileInputStream(file);
                InputStreamReader inputStreamReader = null;
                try {
                    inputStreamReader = new InputStreamReader(instream, "UTF-8");
                } catch (UnsupportedEncodingException e1) {
                    e1.printStackTrace();
                }
                BufferedReader reader = new BufferedReader(inputStreamReader);
            int length;
            length = reader.read(a,0,32*1024*1024);
        }catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return  content;
    }
    public  static String ReadTxtFile(String strFilePath)
    {
        String path = strFilePath;
        String content = ""; //文件内容字符串
        //打开文件
        File file = new File(path);
        //如果path是传递过来的参数，可以做一个非目录的判断
        if (file.isDirectory())
        {
            Log.d("TestFile", "The File doesn't not exist.");
        }
        else
        {
            try {
                InputStream instream = new FileInputStream(file);
                if (instream != null)
                {
                    InputStreamReader inputreader = new InputStreamReader(instream,"GB2312");
                    BufferedReader buffreader = new BufferedReader(inputreader);
                    String line;
                    //分行读取
                    while (( line = buffreader.readLine()) != null) {
                        content += line + "\n";
                    }
                    instream.close();
                }
            }
            catch (java.io.FileNotFoundException e)
            {
                Log.d("TestFile", "The File doesn't not exist.");
            }
            catch (IOException e)
            {
                Log.d("TestFile", e.getMessage());
            }
        }
        return content;
    }

}